package cn.com.homeyoda.aimate.aihealth.ui.bluetooth;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.airbnb.lottie.LottieDrawable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.ToastUtils;
import com.yasee.yasee.Notify;
import com.yasee.yasee.Yasee;
import com.yasee.yasee.core.configs.BleConfig;
import com.yasee.yasee.core.configs.LogConfig;
import com.yasee.yasee.core.enums.DeviceProcess;
import com.yasee.yasee.core.enums.NotifyType;
import com.yasee.yasee.core.interfaces.NotifyInterface;
import com.yasee.yasee.core.models.AdvertisementData;
import com.yasee.yasee.core.models.NotifyResp;
import com.yasee.yasee.protocols.ble.BleDevice;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityBluetoothSearchBinding;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityBluetoothSuccessBinding;
import cn.com.homeyoda.aimate.aihealth.utils.DateFormatUtil;
import cn.com.homeyoda.aimate.aihealth.utils.DeviceManager;
import cn.com.homeyoda.aimate.aihealth.utils.GradientUtils;
import cn.com.homeyoda.aimate.aihealth.utils.HealthDataProcessor;
import cn.com.homeyoda.aimate.aihealth.utils.JsonFileManager;
import cn.com.homeyoda.aimate.aihealth.utils.PermissionHelper;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.FEEDBACK_SUCCESS;

public class BluetoothSuccessActivity extends BaseActivity<ActivityBluetoothSuccessBinding, BluetoothSuccessModel> {


    private String mac;
    private String model;
    private Timer timer = new Timer();
    private BluetoothDevice bluetoothDevice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    public BluetoothSuccessModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(BluetoothSuccessModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        mac = getIntent().getExtras().getString("mac");
        model = getIntent().getExtras().getString("model");
        bluetoothDevice = DeviceManager.getInstance().getCurrentDeviceList();
        Log.i("huahua","bluetoothDevice====init=="+bluetoothDevice);
        Yasee.getSingle().setContext(getApplicationContext());
        Yasee.getSingle().logConfig = new LogConfig(true,true,true,true);

        Notify.getSingle().listen(_ni);
        Notify.getSingle().listen(_state);
        Notify.getSingle().listen(_binds);
        Notify.getSingle().listen(_bleState);
        initView();
        // 启动定时器：延迟0秒后开始，每秒执行一次
        timer.schedule(timerTask, 0, 3000);
    }

    private void initView() {
        binding.deviceXinghao.setText(model);
        binding.deviceBianhao.setText(mac.replace(":", ""));


        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.wancheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });



    }


    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {

            BleDevice device = new BleDevice(bluetoothDevice,new AdvertisementData(new HashMap<>()));
            Log.i("huahua","device====Timer=="+device);
            Log.d("Timer", "每秒执行一次");
//            BleDevice.current.connect();
//            if (BleDevice.current.state == 0) {
//                BleDevice.current.connect();
//            }
        }
    };
    NotifyInterface _binds = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.bindDevices;
        }
        @Override
        public void message(NotifyResp data) {
            Log.i("huahua", "messagesucess: 绑定变化");
            //MainActivity.binds.addAll((List<BleDevice>) data.data);
//            myAdapter.setItems((List<BleDevice>) data.data);
        }
    };

    NotifyInterface _bleState = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.bleState;
        }
        @Override
        public void message(NotifyResp data) {
            NotifyResp.BleLink bleLink = (NotifyResp.BleLink) data.data;
            Log.i("huahua","bleState===="+bleLink.process);
            if(bleLink.process == DeviceProcess.unlink){

            }

        }
    };

    NotifyInterface _state = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.deviceLink;
        }
        @Override
        public void message(NotifyResp data) {
            NotifyResp.BleLink bleLink = (NotifyResp.BleLink) data.data;
            Log.i("huahua","bleLink.process===="+bleLink.process);
            if(bleLink.process == DeviceProcess.unlink){

            }

        }
    };

    NotifyInterface _ni = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.deviceData;
        }

        @Override
        public void message(NotifyResp data) {
            if(binding== null) return;
            NotifyResp.BleNotifyData ssss = (NotifyResp.BleNotifyData) data.data;



            String _s = ssss.dataToJson();
            Log.i("huahua","data==success=="+_s);
            onDataReceived(_s);
        }
    };

    /**
     * 处理接收到的数据
     */
    public void onDataReceived(String jsonString) {
        HealthDataProcessor.ProcessResult result =
                HealthDataProcessor.processHealthData(jsonString);

        switch (result.resultType) {
            case SUCCESS:
                handleSuccessData(result);
                break;
            case ERROR:
                handleErrorData(result);
                break;
            case IGNORED:
                // 忽略无用数据
                Log.d("HealthMonitor", "忽略中间数据: " + result.dataType);
                break;
            case UNKNOWN:
                handleUnknownData(result);
                break;
        }
    }

    /**
     * 处理成功数据
     */
    private void handleSuccessData(HealthDataProcessor.ProcessResult result) {
        runOnUiThread(() -> {
            try {
                switch (result.dataType) {
                    case BLOOD_PRESSURE:
                        updateBloodPressureUI(result.data);
                        break;
                    case BLOOD_SUGAR:
                        updateBloodSugarUI(result.data);
                        break;
                    case BLOOD_KETONE:
                        updateBloodKetoneUI(result.data);
                        break;
                    case URIC_ACID:
                        updateUricAcidUI(result.data);
                        break;
                }
                showToast(result.dataType + "测量完成");
            } catch (Exception e) {
                e.printStackTrace();
                showToast("数据解析失败");
            }
        });
    }

    /**
     * 处理失败数据
     */
    private void handleErrorData(HealthDataProcessor.ProcessResult result) {
        runOnUiThread(() -> {
            String errorMsg = result.data.optString("suggestion",
                    result.data.optString("desc", result.dataType + "测量失败"));
            showToast(errorMsg);
        });
    }

    /**
     * 处理未知数据
     */
    private void handleUnknownData(HealthDataProcessor.ProcessResult result) {
        Log.w("HealthMonitor", "未知数据类型: " + result.data);
    }

    /**
     * 更新血压UI
     */
    private void updateBloodPressureUI(JSONObject data) throws JSONException {
        String systolic = data.getString("systolic");
        String diastolic = data.getString("diastolic");
        String pulse = data.optString("pulse", "0");
        binding.xueya.setText("收缩压 "+systolic+"，"+"舒张压 "+diastolic);
        binding.xueyaTime.setText(DateFormatUtil.getDateTimeNow());
        binding.relXueya.setVisibility(View.VISIBLE);
    }

    /**
     * 更新血糖UI
     */
    private void updateBloodSugarUI(JSONObject data) throws JSONException {
        String value = data.getString("value");
        double number = Double.parseDouble(value);
        DecimalFormat df = new DecimalFormat("0.0");
        String result = df.format(number);
        String displayText = String.format("%s mmol/L", result);
        binding.xuetang.setText(displayText);
        binding.xuetangTime.setText(DateFormatUtil.getDateTimeNow());
        binding.relXuetang.setVisibility(View.VISIBLE);
    }

    /**
     * 更新血酮UI
     */
    private void updateBloodKetoneUI(JSONObject data) throws JSONException {
        String value = data.getString("value");
        double number = Double.parseDouble(value);
        DecimalFormat df = new DecimalFormat("0.0");
        String result = df.format(number);
        String displayText = String.format("%s mmol/L", result);
        binding.xuetong.setText(displayText);
        binding.xuetongTime.setText(DateFormatUtil.getDateTimeNow());
        binding.relXuetong.setVisibility(View.VISIBLE);
    }

    /**
     * 更新尿酸UI
     */
    private void updateUricAcidUI(JSONObject data) throws JSONException {
        String value = data.getString("value");
        double number = Double.parseDouble(value);
        long result = Math.round(number);
        String displayText = String.format("%s μmol/L", result);
        binding.niaosuan.setText(displayText);
        binding.niaosuanTime.setText(DateFormatUtil.getDateTimeNow());
        binding.relNiaosuan.setVisibility(View.VISIBLE);
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();

        LiveEventBus.get(FEEDBACK_SUCCESS, boolean.class).observe(this, aBoolean -> {
            finish();
        });

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_bluetooth_success;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
